package com.hotel.front;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.POSgenerateOrderLogic;

import data.POSCalTax;
import data.POSGuestTable;
import data.POSHistory;
import data.POSOrder;
import data.POSorderItem;
import data.passingData.POSEditOrderItem;
import data.passingData.POSGuestTableData;
import data.passingData.ResultData;
@SuppressWarnings("serial")
public class POSgenerateOrderService extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String func = req.getParameter("func");
			if(func.equals("CreatePOSorderItem")){
				CreatePOSorderItem(req,resp);
			}else if(func.equals("CreatePOSguestTable")){
				CreatePOSguestTable(req,resp);
			}else if(func.equals("LoadPOSguestTable")){
				LoadPOSguestTable(req,resp);
			//}else if(func.equals("EditQuantityOrderItem")){
			//	EditQuantityOrderItem(req,resp);
			//}else if(func.equals("EditDiscountOrderItem")){
			//	EditDiscountOrderItem(req,resp);
			}else if(func.equals("GetPOSHistory")){
				GetPOSHistory(req,resp);
			}else if(func.equals("GetAllPOSHistory")){
				GetAllPOSHistory(req,resp);
			}else if(func.equals("EditPOSguestTable")){
				EditPOSguestTable(req,resp);
			}else if(func.equals("AddPOSReasonCancel")){
				AddPOSReasonCancel(req,resp);			
			}else if(func.equals("GetPOSOrderList")){
				GetPOSOrderList(req,resp);
			}else if(func.equals("AddNote")){
				AddNote(req,resp);
			}else if(func.equals("EditOrder")){
				EditOrder(req,resp);
			}else if(func.equals("CancelOrder")){
				CancelOrder(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void CreatePOSorderItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, EntityNotFoundException{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String outerArray=req.getParameter("orderitemAny");
		String t = req.getParameter("t");
		String PresId = req.getParameter("PresId");
		HashMap<String,Object> g = new POSgenerateOrderLogic(req,resp).AddPOSorder(outerArray,t,PresId);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	
	public void GetPOSOrderList(HttpServletRequest req, HttpServletResponse resp) throws Exception{
		long gtableid= Long.parseLong(req.getParameter("gtableid"));
		List<HashMap<String,Object>> g = new POSgenerateOrderLogic(req,resp).GetPOSOrderList(gtableid);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	
	public void CreatePOSguestTable(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, EntityNotFoundException, ParseException{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String table=req.getParameter("tableId");
		String name = req.getParameter("gName");
		String timeArrive =req.getParameter("timeA");
		String tel =req.getParameter("guestTel");
		String guestAmount =req.getParameter("guestAmt");
		String note =req.getParameter("note");
		POSGuestTableData g=new POSgenerateOrderLogic(req,resp).AddGuestTable(name, timeArrive, tel, guestAmount, table, note);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	
	public void LoadPOSguestTable(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, EntityNotFoundException, ParseException{
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
		Date serverDate = new GenericLogic(req,resp).ServerDateTime(hotelId);
		String t = df.format(serverDate);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
		Date dateform =formatter.parse(t);
		Date dateto=new Date(formatter.parse(t).getTime()+86400000);
		List<POSGuestTable> guestT =new POSgenerateOrderLogic(req,resp).GetPOSGuestTableAll(dateto,dateform);
		List<POSGuestTableData> list = new ArrayList<POSGuestTableData>();
		if(guestT.size()!=0){
			for(POSGuestTable gt:guestT){
				POSGuestTableData pd = new POSGuestTableData();
					pd.setId(gt.getId());
					if(gt.getGuest()!=null)pd.setName(gt.getGuest().getName());
					pd.setStatus(gt.getGuestStatus());
					pd.setArrivel(gt.getArrive());
					pd.setTableId(gt.getTableString());	
					if(gt.getPOSorderListString()!=null){pd.setHaveOrder(true);}else{pd.setHaveOrder(false);}
					if(gt.getGuest()!=null)pd.setTel(gt.getGuest().getPhoneNumber());
					pd.setNote(gt.getNote());
					pd.setGuest(gt.getGuestAmount());
					double money =0;
					if(gt.getPOSorderList()!=null){
						for(POSOrder d:gt.getPOSorderList()){
							if(!d.isStatus()) continue;
							for(POSorderItem i:d.getReloadItem()){
								money += (i.getPrice() * i.getAmount()) - i.getDiscount();
								List<POSCalTax> calTax = i.getTax();
								if(calTax!=null)
									for(POSCalTax tax : calTax)
										money += tax.getTaxValue() * i.getAmount();
							}
						}
					}
					pd.setMoney(money);
					list.add(pd);
			}
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	public void EditPOSguestTable(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, EntityNotFoundException, ParseException{
		String name = req.getParameter("gName");
		String timeArrive =req.getParameter("timeA");
		String tel =req.getParameter("guestTel");
		String guestAmount =req.getParameter("guestAmt");
		String note =req.getParameter("note");
		String resId = req.getParameter("resId");
		POSGuestTableData g=new POSgenerateOrderLogic(req,resp).EditGuestTable(name, timeArrive, tel, guestAmount, note,resId);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	
	public void AddPOSReasonCancel(HttpServletRequest req, HttpServletResponse resp) throws NumberFormatException, EntityNotFoundException, IOException{
		HttpSession session=req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
		hotelId = (Long) session.getAttribute("hotelId");
		String Posresid = req.getParameter("Posresid");
		String reason =req.getParameter("reason");
		String detail =req.getParameter("detail");
		long g=new POSgenerateOrderLogic(req,resp).CancelPOSReservation( hotelId, Long.parseLong(Posresid), reason, detail);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	/*public void EditQuantityOrderItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, EntityNotFoundException
	{
		long gtableId = Long.parseLong(req.getParameter("gtableId"));
		long itemId = Long.parseLong(req.getParameter("itemId"));
		long amount = Long.parseLong(req.getParameter("amount"));
		HashMap<String,Object> rs = new POSgenerateOrderLogic(req,resp).AddEditOrderItemAmount(gtableId, itemId, amount);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rs));
	}

	public void EditDiscountOrderItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, EntityNotFoundException
	{
		HttpSession session=req.getSession(true);
		long gtableId = Long.parseLong(req.getParameter("gtableId"));
		long itemId = Long.parseLong(req.getParameter("itemId"));
		double discount = Double.parseDouble(req.getParameter("discount"));
		HashMap<String,Object> rs = new POSgenerateOrderLogic(req,resp).AddEditOrderItemDiscount(gtableId, itemId, discount,session);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rs));
	}*/
	
	public void GetAllPOSHistory(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		long guestTableId = Long.parseLong(req.getParameter("guestTableId"));
		POSGuestTable posGuestTable = new POSgenerateOrderLogic(req,resp).GetPOSGuestTable(guestTableId);
		List<POSHistory> history = posGuestTable.getPOSHistoryList();
		Collections.sort(history, new Comparator<POSHistory>(){
			  public int compare(POSHistory s1, POSHistory s2) {
			    return (int)(s2.getStampDate().getTime() - s1.getStampDate().getTime());
			  }
			});
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(history));
	}
	
	public void GetPOSHistory(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		long guestTableId = Long.parseLong(req.getParameter("guestTableId"));
		POSGuestTable posGuestTable = new POSgenerateOrderLogic(req,resp).GetPOSGuestTable(guestTableId);
		List<POSHistory> history = posGuestTable.getPOSLastHistoryList(1);
		HashMap<String,Object> hash = new HashMap<String,Object>();
		hash.put("count", posGuestTable.getPOSHistoryListString().split(",").length);
		hash.put("data", history);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(hash));
	}
	
	public void AddNote(HttpServletRequest req, HttpServletResponse resp) throws IOException, EntityNotFoundException
	{
		long posresid = Long.parseLong(req.getParameter("posresid"));
		String title = req.getParameter("title");
		POSGuestTable posGuestTable = new POSgenerateOrderLogic(req,resp).AddNote(posresid,title);
		List<POSHistory> history = posGuestTable.getPOSLastHistoryList(1);
		HashMap<String,Object> hash = new HashMap<String,Object>();
		hash.put("count", posGuestTable.getPOSHistoryListString().split(",").length);
		hash.put("data", history);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(hash));
	}
	
	public void EditOrder(HttpServletRequest req, HttpServletResponse resp) throws Exception
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long posOrderId = Long.parseLong(req.getParameter("orderId"));
		String items = req.getParameter("items");
		Type listType = new TypeToken<List<POSEditOrderItem>>() {}.getType();
		List<POSEditOrderItem> itemList = gson.fromJson(items, listType);
		
		HashMap<String,Object> rs = new POSgenerateOrderLogic(req,resp).EditOrderItem(posOrderId, itemList);
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rs));
	}
	
	private void CancelOrder(HttpServletRequest req, HttpServletResponse resp) throws Exception
	{
		Gson gson = new Gson();
		long posOrderId = Long.parseLong(req.getParameter("orderId"));
		POSOrder order = new POSgenerateOrderLogic(req,resp).CancelOrder(posOrderId);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(order));
	}
}
